import MockAdapter from 'axios-mock-adapter';

// 导入各模块Mock
import userMocks from './modules/user';
import caseMocks from './modules/case';
import lawyerMocks from './modules/lawyer';
import authMocks from './modules/auth';

// 全局Mock配置状态
let isMockEnabled = true;
let mockAdapter = null;

/**
 * 初始化Mock配置
 * @param {AxiosInstance} axiosInstance - Axios实例
 * @returns {MockAdapter} Mock适配器实例
 */
export const setupMock = (axiosInstance) => {
  // 创建Mock适配器
  mockAdapter = new MockAdapter(axiosInstance, {
    delayResponse: Number(import.meta.env.VITE_MOCK_DELAY || 500)
  });

  // 初始化各模块Mock
  authMocks(mockAdapter);
  userMocks(mockAdapter);
  caseMocks(mockAdapter);
  lawyerMocks(mockAdapter);
  
  // 全局捕获未定义的API请求
  mockAdapter.onAny().reply(config => {
    console.warn(`[Mock] 未定义的API请求: ${config.method} ${config.url}`);
    return [404, { 
      code: 404,
      message: 'Mock未定义此接口',
      config 
    }];
  });

  // 开发环境打印Mock信息
  if (import.meta.env.DEV) {
    console.log('[Mock] Mock适配器已启动，拦截模式已启用');
  }

  return mockAdapter;
};

// Mock开关控制函数
export function toggleMock() {
  if (!mockAdapter) {
    console.warn('[Mock] Mock适配器未初始化');
    return;
  }
  
  isMockEnabled = !isMockEnabled;
  
  if (isMockEnabled) {
    mockAdapter.restore();
    console.log('[Mock] 启用模拟数据');
  } else {
    mockAdapter.reset();
    console.log('[Mock] 禁用模拟数据');
  }
}

// 获取Mock状态
export function getMockStatus() {
  return isMockEnabled;
}

// 重置Mock数据
export function resetMockData() {
  if (mockAdapter) {
    mockAdapter.reset();
    console.log('[Mock] 重置模拟数据');
  }
}

// 设置Mock延迟
export function setMockDelay(delay) {
  if (mockAdapter) {
    mockAdapter.restore();
    mockAdapter = new MockAdapter(mockAdapter.axiosInstance, {
      delayResponse: delay
    });
    console.log(`[Mock] 设置延迟为 ${delay}ms`);
  }
} 